import { useEffect, useRef } from 'react'
import * as THREE from 'three'

// 导入GLSL文件
import vertexShader from '@/shaders/vertex.glsl'
import fragmentShader from '@/shaders/fragment.glsl'

const ThreeScene = () => {
    const mountRef = useRef(null)

    useEffect(() => {
        // 创建场景、相机和渲染器
        const scene = new THREE.Scene()
        const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
        camera.position.z = 3

        const renderer = new THREE.WebGLRenderer({ antialias: true })
        renderer.setSize(window.innerWidth, window.innerHeight)
        mountRef.current.appendChild(renderer.domElement)

        // 创建立方体几何体并应用自定义着色器材质
        const geometry = new THREE.BoxGeometry(1, 1, 1)
        const material = new THREE.ShaderMaterial({
            vertexShader,
            fragmentShader,
        })

        const cube = new THREE.Mesh(geometry, material)
        scene.add(cube)

        // 动画循环
        const animate = () => {
            requestAnimationFrame(animate)

            // 让立方体旋转
            cube.rotation.x += 0.01
            cube.rotation.y += 0.01

            renderer.render(scene, camera)
        }
        animate()

        // 清理
        return () => {
            mountRef.current.removeChild(renderer.domElement)
        }
    }, [])

    return <div ref={mountRef} />
}

export default ThreeScene
